package czk.concrent.enjoyModelWithNotLock.lockCas.practice;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义锁的实现
 *
 * @Author:ChenZhangKun
 * @Date: 2020/11/2 22:08
 */
public class LockCasDemo {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    // 加锁方法
    public void lock() {
        while (true) {
            if (atomicInteger.compareAndSet(0, 1)) {
                // 加锁成功
                break;
            }
        }
    }

    // 解锁
    public void unlock() {
        atomicInteger.set(0);
    }

    public static void main(String[] args) throws InterruptedException {
        LockCasDemo lockCasDemo = new LockCasDemo();
        new Thread(() -> {
            lockCasDemo.lock();
            System.out.println("得到锁");
        }).start();
        new Thread(() -> {
            System.out.println("阻塞中");
            lockCasDemo.lock();
            System.out.println("我终于获得锁了");
        }).start();
        TimeUnit.SECONDS.sleep(5);
        lockCasDemo.unlock();
    }
}
